package com.mairuide.one_click_search.service;

import com.mairuide._frame.utils.ListUtils;
import com.mairuide.entity.PageResult;
import com.mairuide.one_click_search.dao.DataSourceDao;
import com.mairuide.one_click_search.dto.DataTemplateDto;
import com.mairuide.one_click_search.pojo.DataSource;
import com.mairuide.one_click_search.pojo.DataTemplateField;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.lang.reflect.Field;
import java.util.*;

/**
 * @Description
 * @auther 刘中华
 * @create 2019-04-23 16:14
 */
@Service
@Transactional
public class DataSourceService {
    private Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    DataSourceDao dataSourceDao;
    @Autowired
    DataTemplateFieldService dataTemplateFieldService;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private RestTemplate restTemplate;
    /**
     * @Author 刘中华
     * @Date 2019/4/29 15:21
     * @Param [tableName]
     * @return java.util.List<com.mairuide.one_click_search.pojo.DataSource>
     * @Description 得到数据列表
     **/
   public PageResult getListByTableName(DataTemplateDto dataTemplateDto, int page, int size){
       Sort sort = new Sort(Sort.Direction.DESC,"vid");
       Specification<DataSource> specification = createSpecification(dataTemplateDto);
       PageRequest pageRequest = new PageRequest(page-1<0?0:page-1,size,sort);
       Page<DataSource> all = dataSourceDao.findAll(specification, pageRequest);
       List<DataSource> sourceList = all.getContent();
       Map<String, String> map = dataTemplateFieldService.findDataTemplateFieldMapByTableName(dataTemplateDto.getTablename());
       ArrayList<Map<String, Object>> maps = new ArrayList<>();
       for (int i = 0; i < sourceList.size(); i++) {
           DataSource source = sourceList.get(i);
           Map<String, Object> m = reflect(source, map);
           if (m!=null){
               maps.add(m);
           }
       }
       HashMap<String, Object> map2 = new HashMap<>();
       //获取字段列表
       if(maps.size()>0){
           List<DataTemplateField> dataTemplateFieldListByTableName = dataTemplateFieldService.findDataTemplateFieldListByTableName(dataTemplateDto.getTablename());
           ArrayList<String> fieldList = new ArrayList<>();
           ArrayList<Integer> widthList = new ArrayList<>();
           for (int i = 0; i < dataTemplateFieldListByTableName.size(); i++) {
               DataTemplateField field = dataTemplateFieldListByTableName.get(i);
               fieldList.add(field.getFiledname());
               widthList.add(field.getColwidth());
           }
           map2.put("field",fieldList);
           map2.put("width",widthList);
       }
       PageResult pageResult = new PageResult(all.getTotalElements(),maps,map2);
       return pageResult;
   }
    /**
     * 动态条件构建
     * @param searchMap
     * @return
     */
    private Specification<DataSource> createSpecification(DataTemplateDto dataTemplateDto) {
        return new Specification<DataSource>() {
            @Override
            public Predicate toPredicate(Root<DataSource> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                List<Predicate> predicateList = new ArrayList<Predicate>();
                if (StringUtils.isNotBlank(dataTemplateDto.getTablename())) {
                    predicateList.add(cb.equal(root.get("tablename").as(String.class), dataTemplateDto.getTablename()));
                }
                predicateList.add(cb.equal(root.get("isDelete").as(Integer.class), 0));
                return cb.and( predicateList.toArray(new Predicate[predicateList.size()]));
            }
        };

    }
    public <T> Map<String, Object> reflect(T e,Map<String,String> map){
        try {
            HashMap<String, Object> m = new LinkedHashMap<>();
            Class cls = e.getClass();
            Field[] fields = cls.getDeclaredFields();
            for(int i=0; i<fields.length; i++){
                Field f = fields[i];
                f.setAccessible(true);
                String key = f.getName();
                Object o = f.get(e);
                if (key==null) continue;
                if (map.containsKey(key)){
                    String  k = map.get(key);
                    m.put(k,o);
                }
            }
            return m;
        } catch (IllegalAccessException e1) {
            e1.printStackTrace();
        }
        return null;
    }

    /**
     * @Author 刘中华
     * @Date 2019/5/7 14:19
     * @Param [ids]
     * @return java.util.List<com.mairuide.one_click_search.pojo.DataSource>
     * @Description 根据主键id集合得到数据
     **/
    public List<DataSource> getDataSourceByIds(String ids,String tableName,Integer type){
        List<DataSource> all = new ArrayList<>();
        StringBuffer sb= new StringBuffer();
        if (type==0){
            sb.append("select * from TB_DATA_SOURCE where is_delete=0 and TABLENAME='"+tableName+"' and vid in ( ");
            String[] idArr = ids.split(",");
            List<String> idList = Arrays.asList(idArr);
            List<List<String>> listList = ListUtils.splitList2(idList, 1000);
            for (int i = 0; i < listList.size(); i++) {
                List<String> list = listList.get(i);
                sb.append(StringUtils.join(list,",") +" ) ");
                List<DataSource> query = jdbcTemplate.query(sb.toString(), new BeanPropertyRowMapper<>(DataSource.class));
                all.addAll(query);
            }
        }else{
            sb.append("select * from TB_DATA_SOURCE where is_delete=0 and TABLENAME='"+tableName+"'");
            all = jdbcTemplate.query(sb.toString(), new BeanPropertyRowMapper<>(DataSource.class));
        }
        return all;
    }

    /**
     * @Author 刘中华
     * @Date 2019/5/20 15:58
     * @Param []
     * @return void
     * @Description 同步solr数据
     **/
    public void synchronizationSolrData(){
        String URL= "http://localhost:8983/solr/MRD-7800/dataimport?command=delta-import&clean=false&commit=true";
        String forObject = restTemplate.getForObject(URL, String.class);
        logger.info("solr同步数据成功。返回值为：》》》》"+forObject);
    }
}
